<?php

namespace app\storeapi\controller;

use app\storeapi\model\Wxapp as WxappModel;
use app\common\exception\BaseException;
use app\storeapi\model\User;
use app\storeapi\model\Base;
use app\storeapi\model\store\User as StoreUser;
use app\storeapi\model\store\Clerk as ClerkUser;
use org\Redis;
/**
 * STOREAPI控制器基类
 * Class BaseController
 * @package app\storeapi\controller
 */
class Controller extends \think\Controller
{
    /** @var string $route 当前控制器名称 */
    protected $controller = '';

    /** @var string $route 当前方法名称 */
    protected $action = '';

    /** @var string $route 当前路由uri */
    protected $routeUri = '';

    protected $notLayoutAction = [
        'passport/login',  // 登录页面
        'passport/forgetpass',  //忘记密码
        'oauth/login',  //授权登录
    ];

    //成功code
    const JSON_SUCCESS_STATUS = 1;
    //错误信息code
    const JSON_ERROR_STATUS = 0;
    //会话过期code
    const JSON_ERROR_LOGIN = -1;

    /* @ver $wxapp_id 小程序id */
    protected $wxapp_id;

    protected $model;

    /**
     * API基类初始化
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {

        // 控制器名称
        $this->controller = toUnderScore($this->request->controller());
        // 方法名称
        $this->action = $this->request->action();
        //当前路由uri
        $this->routeUri = $this->controller . '/' . $this->action;

        // 验证当前请求是否在白名单
        if (!in_array($this->routeUri, $this->notLayoutAction)) {

            $this->model = new Base();
            //判断是否登录以及用户状态
            $this->checkLogin();
            // 当前小程序id
            $this->wxapp_id = $this->getWxappId();
            // 验证当前小程序状态
            $this->checkWxapp();
        }
    }

    /**
     * 判断是否登录
     * @return mixed
     * @throws BaseException
     */
    private function checkLogin()
    {
        //获取缓存
        $redis = new Redis();
        if (!$token = $this->request->param('token')) {
            throw new BaseException(['msg' => $this->model::ERROR_MSG_TOKEN]);
        }
        $userRedis = $redis->get($token);
        //重新登录
        if(!$userRedis) $this->throwError($this->model::ERROR_MSG_LOGIN,self::JSON_ERROR_LOGIN);

        if($userRedis['identity']==1){
            $model = new StoreUser;
        }elseif($userRedis['identity']==2){
            $model = new ClerkUser;
        }
        if(!$model->checkState($userRedis['login_user_id'])){
            throw new BaseException(['msg' => $model->getError()]);
        }

    }


    /**
     * 获取当前小程序ID
     * @return mixed
     * @throws BaseException
     */
    private function getWxappId()
    {

        if (!$wxapp_id = $this->request->param('wxapp_id')) {

            throw new BaseException(['msg' => $this->model::ERROR_MSG_APPID]);
        }
        return $wxapp_id;
    }

    /**
     * 验证当前小程序状态
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function checkWxapp()
    {
        $wxapp = WxappModel::detail($this->wxapp_id);
        if (empty($wxapp)) {
            throw new BaseException(['msg' => $this->model::ERROR_MSG_NOFIND]);
        }
        if ($wxapp['is_recycle'] || $wxapp['is_delete']) {
            throw new BaseException(['msg' => $this->model::ERROR_MSG_NOFIND]);
        }
        if (!$wxapp['active']) {
            throw new BaseException(['msg' => $this->model::ERROR_MSG_ACTIVE]);
        }
    }


    /**
     * 输出错误信息
     * @param int $code
     * @param $msg
     * @throws BaseException
     */
    protected function throwError($msg, $code = 0)
    {
        throw new BaseException(['code' => $code, 'msg' => $msg]);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderJson($code = self::JSON_SUCCESS_STATUS, $msg = '', $data = [])
    {
        return compact('code', 'msg', 'data');
    }

    /**
     * 返回操作成功json
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function renderSuccess($data = [], $msg = '查询成功')
    {
        return $this->renderJson(self::JSON_SUCCESS_STATUS, $msg, $data);
    }

    /**
     * 返回操作失败json
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderError($msg = 'error', $data = [])
    {
        return $this->renderJson(self::JSON_ERROR_STATUS, $msg, $data);
    }

    /**
     * 获取post数据 (数组)
     * @param $key
     * @return mixed
     */
    protected function postData($key = null)
    {
        return $this->request->post(is_null($key) ? '' : $key . '/a');
    }

}
